package com.aismy.admin.service.impl;

import com.aismy.admin.dto.ArticleDTO;
import com.aismy.admin.entity.Article;
import com.aismy.admin.entity.SysUser;
import com.aismy.admin.mapper.ArticleMapper;
import com.aismy.admin.service.ArticleService;
import com.aismy.admin.service.UserService;

import com.aismy.admin.vo.ArticleVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;



import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Resource
    private UserService userService;

    @Override
    @Transactional
    public Long createArticle(ArticleDTO articleDTO, Long userId) {
        Article article = new Article();
        BeanUtils.copyProperties(articleDTO, article);
        article.setUserId(userId);
        article.setViewCount(0);
        article.setLikeCount(0);
        article.setCommentCount(0);
        article.setStatus(1);
        
        save(article);
        return article.getId();
    }

    @Override
    @Transactional
    public void updateArticle(ArticleDTO articleDTO, Long userId) {
        Article article = getById(articleDTO.getId());
        if (article == null || !article.getUserId().equals(userId)) {
            throw new RuntimeException("无权修改此文章");
        }
        
        BeanUtils.copyProperties(articleDTO, article);
        updateById(article);
    }

    @Override
    @Transactional
    public void deleteArticle(Long id, Long userId) {
        Article article = getById(id);
        if (article == null || !article.getUserId().equals(userId)) {
            throw new RuntimeException("无权删除此文章");
        }
        
        article.setStatus(2); // 设置为已删除
        updateById(article);
    }

    @Override
    public ArticleVO getArticleDetail(Long id) {
        Article article = getById(id);
        if (article == null || article.getStatus() == 2) {
            throw new RuntimeException("文章不存在");
        }
        
        ArticleVO vo = new ArticleVO();
        BeanUtils.copyProperties(article, vo);
        
        // 获取作者信息
        SysUser author = userService.getById(article.getUserId());
        if (author != null) {
            vo.setAuthorName(author.getUsername());
            vo.setAuthorAvatar(author.getAvatar());
        }
        
        return vo;
    }

    @Override
    public Page<ArticleVO> getArticleList(Integer page, Integer size) {
        Page<Article> articlePage = page(new Page<>(page, size),
                new LambdaQueryWrapper<Article>()
                        .eq(Article::getStatus, 1)
                        .orderByDesc(Article::getCreatedAt));
        
        return convertToVOPage(articlePage);
    }

    @Override
    public Page<ArticleVO> getUserArticles(Long userId, Integer page, Integer size) {
        Page<Article> articlePage = page(new Page<>(page, size),
                new LambdaQueryWrapper<Article>()
                        .eq(Article::getUserId, userId)
                        .eq(Article::getStatus, 1)
                        .orderByDesc(Article::getCreatedAt));
        
        return convertToVOPage(articlePage);
    }
    
    private Page<ArticleVO> convertToVOPage(Page<Article> articlePage) {
        List<Article> records = articlePage.getRecords();
        if (records.isEmpty()) {
            return new Page<ArticleVO>().setTotal(0);
        }
        
        // 获取所有作者信息
        List<Long> userIds = records.stream()
                .map(Article::getUserId)
                .distinct()
                .collect(Collectors.toList());
        
        Map<Long, SysUser> userMap = userService.listByIds(userIds).stream()
                .collect(Collectors.toMap(SysUser::getId, user -> user));
        
        // 转换为VO
        List<ArticleVO> voList = records.stream().map(article -> {
            ArticleVO vo = new ArticleVO();
            BeanUtils.copyProperties(article, vo);

            SysUser author = userMap.get(article.getUserId());
            if (author != null) {
                vo.setAuthorName(author.getUsername());
                vo.setAuthorAvatar(author.getAvatar());
            }
            
            return vo;
        }).collect(Collectors.toList());
        
        Page<ArticleVO> voPage = new Page<>();
        BeanUtils.copyProperties(articlePage, voPage, "records");
        voPage.setRecords(voList);
        
        return voPage;
    }

    @Override
    public List<ArticleVO> getLatestArticles(int limit) {
        // 获取最新的文章列表
        List<Article> articles = list(new LambdaQueryWrapper<Article>()
                .eq(Article::getStatus, 1)
                .orderByDesc(Article::getCreatedAt)
                .last("LIMIT " + limit));

        if (articles.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取作者信息
        List<Long> userIds = articles.stream()
                .map(Article::getUserId)
                .distinct()
                .collect(Collectors.toList());

        Map<Long, SysUser> userMap = userService.listByIds(userIds).stream()
                .collect(Collectors.toMap(SysUser::getId, user -> user));

        // 转换为VO
        return articles.stream().map(article -> {
            ArticleVO vo = new ArticleVO();
            BeanUtils.copyProperties(article, vo);

            SysUser author = userMap.get(article.getUserId());
            if (author != null) {
                vo.setAuthorName(author.getUsername());
                vo.setAuthorAvatar(author.getAvatar());
            }

            return vo;
        }).collect(Collectors.toList());
    }
} 